<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>轮胎管理系统 - 费用统计报表</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
  <!-- 引入 jQuery 和 jQuery UI 用于自动补全 -->
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.0/themes/smoothness/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
  <style>
    .status-badge {
      font-size: 0.8rem;
    }
    .table th {
      background-color: #f8f9fa;
    }
    .action-buttons .btn {
      margin-right: 5px;
      margin-bottom: 5px;
    }
    .axle-badge {
      background-color: #6c757d;
    }
    .btn-visualization {
      background-color: #9c27b0;
      border-color: #9c27b0;
      color: white;
    }
    .btn-visualization:hover {
      background-color: #7b1fa2;
      border-color: #7b1fa2;
    }
    .btn-statistics {
      background-color: #28a745;
      border-color: #28a745;
      color: white;
    }
    .btn-statistics:hover {
      background-color: #218838;
      border-color: #1e7e34;
    }
    .btn-cost {
      background-color: #ff9800;
      border-color: #ff9800;
      color: white;
    }
    .btn-cost:hover {
      background-color: #f57c00;
      border-color: #f57c00;
    }
    .ui-autocomplete {
      max-height: 200px;
      overflow-y: auto;
      overflow-x: hidden;
      z-index: 1000;
    }
    .ui-autocomplete-loading {
      background: white url('https://code.jquery.com/ui/1.13.0/themes/smoothness/images/ui-anim_basic_16x16.gif') right center no-repeat;
      background-size: 16px 16px;
    }
    .loading-overlay {
      display: none;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(255, 255, 255, 0.8);
      z-index: 1000;
      justify-content: center;
      align-items: center;
    }
    .cost-summary-card {
      transition: all 0.3s ease;
    }
    .cost-summary-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    .chart-container {
      height: 300px;
      margin-bottom: 20px;
    }
    .table-costs th {
      background-color: #e9ecef;
    }
    .cost-positive {
      color: #dc3545;
      font-weight: bold;
    }
    .cost-negative {
      color: #28a745;
      font-weight: bold;
    }
    .summary-card {
      border-left: 4px solid;
    }
    .summary-card.total {
      border-left-color: #007bff;
    }
    .summary-card.purchase {
      border-left-color: #28a745;
    }
    .summary-card.repair {
      border-left-color: #ffc107;
    }
    .summary-card.other {
      border-left-color: #17a2b8;
    }
    .trend-up {
      color: #dc3545;
    }
    .trend-down {
      color: #28a745;
    }
    .filter-section {
      background-color: #f8f9fa;
      border-radius: 5px;
      padding: 20px;
      margin-bottom: 20px;
    }
  </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <div class="container">
    <a class="navbar-brand" href="/api/tires">轮胎管理系统</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav me-auto">
        <li class="nav-item">
          <a class="nav-link" href="/api/tires">轮胎列表</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/api/tires/batch-add">批量添加轮胎</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/api/tires/usage">查询使用记录</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/api/tires/visualization/">轮胎可视化</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/api/tires/statistics">轮胎统计</a>
        </li>
        <li class="nav-item">
          <a class="nav-link active" href="/api/tires/cost-statistics">费用统计报表</a>
        </li>
      </ul>
    </div>
  </div>
</nav>

<div class="container mt-4">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <h1>费用统计报表</h1>
    <div>
      <button type="button" class="btn btn-success" onclick="exportCostStatistics()">
        <i class="fas fa-download"></i> 导出Excel
      </button>
      <button type="button" class="btn btn-primary" onclick="printReport()">
        <i class="fas fa-print"></i> 打印报表
      </button>
    </div>
  </div>

  <!-- 统计筛选条件 -->
  <div class="filter-section">
    <h5 class="mb-3">统计条件</h5>
    <form id="costStatisticsForm" class="row g-3">
      <div class="col-md-3">
        <label for="statCompany" class="form-label">运输公司</label>
        <select class="form-select" id="statCompany" name="company">
          <option value="">全部公司</option>
          <option th:each="company : ${transportCompanies}"
                  th:value="${company}"
                  th:text="${company}"></option>
        </select>
      </div>
      <div class="col-md-2">
        <label for="statYear" class="form-label">年份</label>
        <select class="form-select" id="statYear" name="year">
          <option value="">全部年份</option>
          <!-- 年份选项将通过JavaScript动态生成 -->
        </select>
      </div>
      <div class="col-md-2">
        <label for="statMonth" class="form-label">月份</label>
        <select class="form-select" id="statMonth" name="month">
          <option value="">全部月份</option>
          <option value="1">1月</option>
          <option value="2">2月</option>
          <option value="3">3月</option>
          <option value="4">4月</option>
          <option value="5">5月</option>
          <option value="6">6月</option>
          <option value="7">7月</option>
          <option value="8">8月</option>
          <option value="9">9月</option>
          <option value="10">10月</option>
          <option value="11">11月</option>
          <option value="12">12月</option>
        </select>
      </div>
      <div class="col-md-3">
        <label for="statType" class="form-label">统计类型</label>
        <select class="form-select" id="statType" name="statType">
          <option value="monthly">月度统计</option>
          <option value="yearly">年度统计</option>
          <option value="vehicle">单车结算</option>
          <option value="company">公司统计</option>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">&nbsp;</label>
        <div>
          <button type="submit" class="btn btn-primary w-100">生成报表</button>
        </div>
      </div>
    </form>
  </div>

  <!-- 费用汇总卡片 -->
  <div class="row mb-4" id="costSummaryCards">
    <!-- 费用汇总卡片将通过JavaScript动态生成 -->
  </div>

  <!-- 统计图表区域 -->
  <div class="row mb-4">
    <div class="col-md-8">
      <div class="card">
        <div class="card-header">
          <h6 class="mb-0">费用趋势图</h6>
        </div>
        <div class="card-body">
          <div class="chart-container">
            <canvas id="costTrendChart"></canvas>
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="card">
        <div class="card-header">
          <h6 class="mb-0">费用分布</h6>
        </div>
        <div class="card-body">
          <div class="chart-container">
            <canvas id="costDistributionChart"></canvas>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 月度对比图表 -->
  <div class="card mb-4">
    <div class="card-header">
      <h6 class="mb-0">月度费用对比</h6>
    </div>
    <div class="card-body">
      <div class="chart-container">
        <canvas id="monthlyComparisonChart"></canvas>
      </div>
    </div>
  </div>

  <!-- 费用明细表格 -->
  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <h6 class="mb-0">费用明细</h6>
      <div>
        <span class="badge bg-primary" id="totalRecords">0 条记录</span>
      </div>
    </div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-striped table-hover mb-0 table-costs" id="costDetailsTable">
          <thead>
          <tr>
            <th>日期</th>
            <th>运输公司</th>
            <th>车牌号</th>
            <th>轮胎号</th>
            <th>费用类型</th>
            <th>金额(元)</th>
            <th>说明</th>
            <th>操作人</th>
          </tr>
          </thead>
          <tbody id="costDetailsBody">
          <!-- 费用明细数据将通过JavaScript动态填充 -->
          </tbody>
        </table>
      </div>
    </div>
    <div class="card-footer">
      <nav>
        <ul class="pagination justify-content-center mb-0" id="pagination">
          <!-- 分页将通过JavaScript动态生成 -->
        </ul>
      </nav>
    </div>
  </div>
</div>

<footer class="bg-dark text-white mt-5 py-4">
  <div class="container text-center">
    <p class="mb-0">轮胎管理系统 &copy; 2025</p>
  </div>
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- 引入Chart.js用于图表展示 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- 引入Font Awesome图标 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/js/all.min.js"></script>

<script>
  // 图表实例
  let costTrendChart = null;
  let costDistributionChart = null;
  let monthlyComparisonChart = null;

  // 分页信息
  let currentPage = 1;
  const pageSize = 10;
  let totalRecords = 0;
  let totalPages = 1;

  // 当前费用汇总数据，用于分布图
  let currentSummary = null;
  // 存储所有费用明细数据用于前端分页
  let allCostDetails = [];

  $(document).ready(function() {
    // 初始化年份选择器
    initYearSelector();
    // 动态加载运输公司列表
    loadTransportCompanies();

    // 费用统计表单提交事件
    $("#costStatisticsForm").submit(function(e) {
      e.preventDefault();
      currentPage = 1;
      loadCostStatistics();
    });

    // 默认加载数据
    loadCostStatistics();

    // 添加键盘导航支持
    document.addEventListener('keydown', function(event) {
      // 左箭头键 - 上一页
      if (event.key === 'ArrowLeft' && currentPage > 1) {
        changePage(currentPage - 1);
      }
      // 右箭头键 - 下一页
      else if (event.key === 'ArrowRight' && currentPage < totalPages) {
        changePage(currentPage + 1);
      }
    });
  });
  // 添加运输公司加载函数
  function loadTransportCompanies() {
    fetch('/api/tires/transport-companies')
            .then(response => {
              if (!response.ok) {
                throw new Error('网络响应不正常');
              }
              return response.json();
            })
            .then(companies => {
              const companySelect = document.getElementById('statCompany');

              // 清空现有选项（除了"全部公司"选项）
              while (companySelect.options.length > 1) {
                companySelect.remove(1);
              }

              // 添加新的运输公司选项
              companies.forEach(company => {
                const option = document.createElement('option');
                option.value = company;
                option.textContent = company;
                companySelect.appendChild(option);
              });

              console.log('加载运输公司列表成功，数量:', companies.length);
            })
            .catch(error => {
              console.error('加载运输公司列表失败:', error);
            });
  }


  // 初始化年份选择器
  function initYearSelector() {
    const yearSelect = document.getElementById('statYear');
    const currentYear = new Date().getFullYear();

    // 清空现有选项（除了第一个）
    while (yearSelect.options.length > 1) {
      yearSelect.remove(1);
    }

    // 生成最近5年的选项
    for (let i = currentYear - 2; i <= currentYear + 2; i++) {
      const option = document.createElement('option');
      option.value = i;
      option.textContent = i + '年';
      yearSelect.appendChild(option);
    }

    // 默认选择当前年份
    yearSelect.value = currentYear;
  }

  // 加载费用统计数据
  function loadCostStatistics() {
    const formData = new FormData(document.getElementById('costStatisticsForm'));
    const params = new URLSearchParams();

    for (const [key, value] of formData.entries()) {
      if (value) params.append(key, value);
    }

    // 显示加载状态
    showLoading();

    // 重置分页到第一页
    currentPage = 1;

    console.log('请求URL:', `/api/tires/cost-statistics/data?${params}`);

    fetch(`/api/tires/cost-statistics/data?${params}`)
            .then(response => {
              console.log('响应状态:', response.status);
              if (!response.ok) {
                throw new Error(`HTTP错误! 状态: ${response.status}`);
              }
              return response.json();
            })
            .then(data => {
              console.log('响应数据:', data);
              updateCostSummary(data.summary);
              updateCharts(data.chartData);

              // 处理费用明细数据
              if (data.details && Array.isArray(data.details)) {
                allCostDetails = data.details;
                totalRecords = allCostDetails.length;
                totalPages = Math.ceil(totalRecords / pageSize);

                // 显示当前页的数据
                updateCostDetails(getCurrentPageData());
                updatePagination();
              } else {
                allCostDetails = [];
                totalRecords = 0;
                totalPages = 1;
                updateCostDetails([]);
                updatePagination();
              }
            })
            .catch(error => {
              console.error('加载费用统计数据失败:', error);
              alert('加载费用统计数据失败: ' + error.message);
              allCostDetails = [];
              totalRecords = 0;
              totalPages = 1;
              updateCostDetails([]);
              updatePagination();
            })
            .finally(() => {
              hideLoading();
            });
  }

  // 获取当前页的数据
  function getCurrentPageData() {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, allCostDetails.length);
    return allCostDetails.slice(startIndex, endIndex);
  }

  // 显示加载状态
  function showLoading() {
    document.getElementById('costDetailsBody').innerHTML = `
      <tr>
        <td colspan="8" class="text-center py-4">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <div class="mt-2">加载中...</div>
        </td>
      </tr>
    `;
  }

  // 隐藏加载状态
  function hideLoading() {
    // 加载状态会在数据更新时被替换
  }

  // 更新费用汇总卡片
  function updateCostSummary(summary) {
    const container = document.getElementById('costSummaryCards');
    container.innerHTML = '';

    // 保存summary数据用于分布图
    currentSummary = summary;

    const cards = [
      {
        title: '总费用',
        value: summary.totalCost || 0,
        color: 'primary',
        icon: 'fa-dollar-sign',
        class: 'total'
      },
      {
        title: '采购费用',
        value: summary.purchaseCost || 0,
        color: 'success',
        icon: 'fa-shopping-cart',
        class: 'purchase'
      },
      {
        title: '维修费用',
        value: summary.repairCost || 0,
        color: 'warning',
        icon: 'fa-tools',
        class: 'repair'
      },
      {
        title: '其他费用',
        value: summary.otherCost || 0,
        color: 'info',
        icon: 'fa-chart-bar',
        class: 'other'
      }
    ];

    cards.forEach(card => {
      const cardHtml = `
        <div class="col-md-3">
          <div class="card summary-card ${card.class}">
            <div class="card-body">
              <div class="d-flex justify-content-between align-items-center">
                <div>
                  <h6 class="card-title text-muted">${card.title}</h6>
                  <h3 class="card-text">¥${typeof card.value === 'number' ? card.value.toLocaleString() : '0'}</h3>
                </div>
                <div class="text-${card.color}">
                  <i class="fas ${card.icon} fa-2x"></i>
                </div>
              </div>
            </div>
          </div>
        </div>
      `;
      container.innerHTML += cardHtml;
    });
  }

  // 更新所有图表 - 适配新的数据结构
  function updateCharts(chartData) {
    console.log('Chart data received:', chartData);

    // 确保chartData存在
    if (!chartData) {
      console.error('Chart data is undefined');
      createEmptyCharts();
      return;
    }

    // 更新各个图表
    updateCostTrendChart(chartData);
    updateCostDistributionChart();
    updateMonthlyComparisonChart(chartData);
  }

  // 创建空图表
  function createEmptyCharts() {
    createEmptyChart('costTrendChart', '费用趋势图数据暂不可用');
    createEmptyChart('costDistributionChart', '费用分布数据暂不可用');
    createEmptyChart('monthlyComparisonChart', '月度对比数据暂不可用');
  }

  // 安全销毁图表函数
  function safeDestroyChart(chartInstance, canvasId) {
    try {
      // 先通过变量销毁
      if (chartInstance) {
        chartInstance.destroy();
        chartInstance = null;
      }

      // 再通过Chart.js的静态方法销毁
      const canvas = document.getElementById(canvasId);
      if (canvas) {
        const existingChart = Chart.getChart(canvas);
        if (existingChart) {
          existingChart.destroy();
        }
      }
    } catch (error) {
      console.warn(`销毁图表 ${canvasId} 时出错:`, error);
    }

    return null;
  }

  // 创建空图表显示提示信息
  function createEmptyChart(canvasId, message) {
    const ctx = document.getElementById(canvasId).getContext('2d');

    // 安全销毁之前的图表实例
    if (canvasId === 'costTrendChart') {
      costTrendChart = safeDestroyChart(costTrendChart, canvasId);
    } else if (canvasId === 'costDistributionChart') {
      costDistributionChart = safeDestroyChart(costDistributionChart, canvasId);
    } else if (canvasId === 'monthlyComparisonChart') {
      monthlyComparisonChart = safeDestroyChart(monthlyComparisonChart, canvasId);
    }

    try {
      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: [message],
          datasets: [{
            label: '无数据',
            data: [0],
            backgroundColor: 'rgba(200, 200, 200, 0.5)'
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    } catch (error) {
      console.error(`创建空图表 ${canvasId} 时出错:`, error);
    }
  }

  // 更新费用趋势图 - 适配新的数据结构
  function updateCostTrendChart(chartData) {
    const ctx = document.getElementById('costTrendChart').getContext('2d');

    // 安全销毁之前的图表实例
    costTrendChart = safeDestroyChart(costTrendChart, 'costTrendChart');

    // 确保数据存在
    const labels = chartData && chartData.labels ? chartData.labels : ['暂无数据'];
    const purchaseData = chartData && chartData.purchaseData ? chartData.purchaseData : [0];
    const repairData = chartData && chartData.repairData ? chartData.repairData : [0];
    const otherData = chartData && chartData.otherData ? chartData.otherData : [0];

    // 计算总费用数据
    const totalData = [];
    const maxLength = Math.max(labels.length, purchaseData.length, repairData.length, otherData.length);

    for (let i = 0; i < maxLength; i++) {
      const purchase = purchaseData[i] || 0;
      const repair = repairData[i] || 0;
      const other = otherData[i] || 0;
      totalData.push(purchase + repair + other);
    }

    try {
      costTrendChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: labels,
          datasets: [
            {
              label: '总费用',
              data: totalData,
              borderColor: '#007bff',
              backgroundColor: 'rgba(0, 123, 255, 0.1)',
              borderWidth: 2,
              fill: true,
              tension: 0.4
            },
            {
              label: '采购费用',
              data: purchaseData,
              borderColor: '#28a745',
              backgroundColor: 'rgba(40, 167, 69, 0.1)',
              borderWidth: 2,
              fill: false,
              tension: 0.4
            },
            {
              label: '维修费用',
              data: repairData,
              borderColor: '#ffc107',
              backgroundColor: 'rgba(255, 193, 7, 0.1)',
              borderWidth: 2,
              fill: false,
              tension: 0.4
            },
            {
              label: '其他费用',
              data: otherData,
              borderColor: '#17a2b8',
              backgroundColor: 'rgba(23, 162, 184, 0.1)',
              borderWidth: 2,
              fill: false,
              tension: 0.4
            }
          ]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            y: {
              beginAtZero: true,
              title: {
                display: true,
                text: '金额(元)'
              }
            }
          },
          plugins: {
            title: {
              display: true,
              text: '费用趋势分析'
            }
          }
        }
      });
    } catch (error) {
      console.error('创建费用趋势图时出错:', error);
      createEmptyChart('costTrendChart', '创建图表失败');
    }
  }

  // 更新费用分布图 - 使用summary数据
  function updateCostDistributionChart() {
    const ctx = document.getElementById('costDistributionChart').getContext('2d');

    // 安全销毁之前的图表实例
    costDistributionChart = safeDestroyChart(costDistributionChart, 'costDistributionChart');

    // 使用汇总数据
    const labels = ['采购费用', '维修费用', '其他费用'];
    const data = [
      currentSummary && currentSummary.purchaseCost ? currentSummary.purchaseCost : 0,
      currentSummary && currentSummary.repairCost ? currentSummary.repairCost : 0,
      currentSummary && currentSummary.otherCost ? currentSummary.otherCost : 0
    ];

    // 如果所有数据都是0，显示提示
    if (data.every(val => val === 0)) {
      createEmptyChart('costDistributionChart', '暂无费用数据');
      return;
    }

    try {
      costDistributionChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
          labels: labels,
          datasets: [{
            data: data,
            backgroundColor: [
              '#28a745',
              '#ffc107',
              '#17a2b8'
            ],
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              position: 'bottom'
            },
            title: {
              display: true,
              text: '费用分布'
            }
          }
        }
      });
    } catch (error) {
      console.error('创建费用分布图时出错:', error);
      createEmptyChart('costDistributionChart', '创建图表失败');
    }
  }

  // 更新月度对比图 - 适配新的数据结构
  function updateMonthlyComparisonChart(chartData) {
    const ctx = document.getElementById('monthlyComparisonChart').getContext('2d');

    // 安全销毁之前的图表实例
    monthlyComparisonChart = safeDestroyChart(monthlyComparisonChart, 'monthlyComparisonChart');

    // 确保数据存在
    const labels = chartData && chartData.labels ? chartData.labels : ['暂无数据'];
    const purchaseData = chartData && chartData.purchaseData ? chartData.purchaseData : [0];
    const repairData = chartData && chartData.repairData ? chartData.repairData : [0];
    const otherData = chartData && chartData.otherData ? chartData.otherData : [0];

    try {
      monthlyComparisonChart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [
            {
              label: '采购费用',
              data: purchaseData,
              backgroundColor: 'rgba(40, 167, 69, 0.8)',
              borderColor: 'rgba(40, 167, 69, 1)',
              borderWidth: 1
            },
            {
              label: '维修费用',
              data: repairData,
              backgroundColor: 'rgba(255, 193, 7, 0.8)',
              borderColor: 'rgba(255, 193, 7, 1)',
              borderWidth: 1
            },
            {
              label: '其他费用',
              data: otherData,
              backgroundColor: 'rgba(23, 162, 184, 0.8)',
              borderColor: 'rgba(23, 162, 184, 1)',
              borderWidth: 1
            }
          ]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            y: {
              beginAtZero: true,
              title: {
                display: true,
                text: '金额(元)'
              }
            }
          },
          plugins: {
            title: {
              display: true,
              text: '月度费用对比'
            }
          }
        }
      });
    } catch (error) {
      console.error('创建月度对比图时出错:', error);
      createEmptyChart('monthlyComparisonChart', '创建图表失败');
    }
  }

  // 更新费用明细表格
  function updateCostDetails(details) {
    const tbody = document.getElementById('costDetailsBody');
    tbody.innerHTML = '';

    if (!details || details.length === 0) {
      tbody.innerHTML = `
        <tr>
          <td colspan="8" class="text-center py-4">
            <div class="text-muted">
              <i class="fas fa-inbox fa-2x mb-3"></i>
              <p>暂无费用数据</p>
            </div>
          </td>
        </tr>
      `;
      return;
    }

    // 显示当前页的数据范围信息
    const startIndex = (currentPage - 1) * pageSize + 1;
    const endIndex = Math.min(currentPage * pageSize, totalRecords);

    // 更新表格标题显示当前显示范围
    const tableHeader = document.querySelector('.card-header h6');
    if (tableHeader) {
      tableHeader.innerHTML = `费用明细 <small class="text-muted">(显示 ${startIndex}-${endIndex} 条，共 ${totalRecords} 条)</small>`;
    }

    details.forEach((detail, index) => {
      const row = document.createElement('tr');

      // 计算实际序号
      const actualIndex = startIndex + index;

      const amount = detail.amount || 0;
      const amountClass = amount >= 0 ? 'cost-positive' : 'cost-negative';
      const amountSign = amount >= 0 ? '+' : '';

      row.innerHTML = `
        <td>${detail.date || '--'}</td>
        <td>${detail.company || '--'}</td>
        <td>${detail.plateNumber || '--'}</td>
        <td>${detail.tireNumber || '--'}</td>
        <td>
          <span class="badge bg-${getCostTypeBadgeColor(detail.costType)}">
            ${detail.costType || '--'}
          </span>
        </td>
        <td class="${amountClass}">${amountSign}¥${typeof amount === 'number' ? amount.toLocaleString() : '0'}</td>
        <td>${detail.description || '--'}</td>
        <td>${detail.operator || '系统'}</td>
      `;
      tbody.appendChild(row);
    });
  }

  // 更新分页函数 - 修复版本
  function updatePagination() {
    const paginationContainer = document.getElementById('pagination');
    const totalRecordsElement = document.getElementById('totalRecords');

    totalRecordsElement.textContent = `${totalRecords.toLocaleString()} 条记录`;

    // 如果总记录数为0，不显示分页
    if (totalRecords === 0) {
      paginationContainer.innerHTML = '';
      return;
    }

    let paginationHTML = '';

    // 上一页按钮
    if (currentPage > 1) {
      paginationHTML += `
      <li class="page-item">
        <a class="page-link" href="#" onclick="changePage(${currentPage - 1}); return false;">« 上一页</a>
      </li>
    `;
    } else {
      paginationHTML += `
      <li class="page-item disabled">
        <span class="page-link">« 上一页</span>
      </li>
    `;
    }

    // 计算要显示的页码范围
    const maxVisiblePages = 5; // 最多显示5个页码
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    // 调整起始页码，确保显示maxVisiblePages个页码
    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    // 第一页和省略号
    if (startPage > 1) {
      paginationHTML += `
      <li class="page-item">
        <a class="page-link" href="#" onclick="changePage(1); return false;">1</a>
      </li>
    `;
      if (startPage > 2) {
        paginationHTML += `
        <li class="page-item disabled">
          <span class="page-link">...</span>
        </li>
      `;
      }
    }

    // 页码按钮
    for (let i = startPage; i <= endPage; i++) {
      if (i === currentPage) {
        paginationHTML += `
        <li class="page-item active">
          <a class="page-link" href="#">${i}</a>
        </li>
      `;
      } else {
        paginationHTML += `
        <li class="page-item">
          <a class="page-link" href="#" onclick="changePage(${i}); return false;">${i}</a>
        </li>
      `;
      }
    }

    // 最后一页和省略号
    if (endPage < totalPages) {
      if (endPage < totalPages - 1) {
        paginationHTML += `
        <li class="page-item disabled">
          <span class="page-link">...</span>
        </li>
      `;
      }
      paginationHTML += `
      <li class="page-item">
        <a class="page-link" href="#" onclick="changePage(${totalPages}); return false;">${totalPages}</a>
      </li>
    `;
    }

    // 下一页按钮
    if (currentPage < totalPages) {
      paginationHTML += `
      <li class="page-item">
        <a class="page-link" href="#" onclick="changePage(${currentPage + 1}); return false;">下一页 »</a>
      </li>
    `;
    } else {
      paginationHTML += `
      <li class="page-item disabled">
        <span class="page-link">下一页 »</span>
      </li>
    `;
    }

    paginationContainer.innerHTML = paginationHTML;
  }

  // 切换页码函数 - 修复版本
  function changePage(page) {
    // 确保页码在有效范围内
    if (page < 1 || page > totalPages || page === currentPage) {
      return;
    }

    currentPage = page;

    // 显示当前页的数据
    updateCostDetails(getCurrentPageData());
    updatePagination();

    // 滚动到表格顶部
    const tableElement = document.getElementById('costDetailsTable');
    if (tableElement) {
      tableElement.scrollIntoView({behavior: 'smooth', block: 'start'});
    }
  }

  // 根据费用类型获取徽章颜色
  function getCostTypeBadgeColor(costType) {
    const colorMap = {
      '采购': 'success',
      '维修': 'warning',
      '安装': 'info',
      '调胎': 'secondary',
      '其他': 'primary'
    };
    return colorMap[costType] || 'primary';
  }

  // 替代方案：使用GET请求，通过URL参数传递汇总数据
  function exportCostStatistics() {
    const formData = new FormData(document.getElementById('costStatisticsForm'));
    const params = new URLSearchParams();

    for (const [key, value] of formData.entries()) {
      if (value) params.append(key, value);
    }

    // 添加汇总数据到参数中
    if (currentSummary) {
      params.append('totalCost', currentSummary.totalCost || 0);
      params.append('purchaseCost', currentSummary.purchaseCost || 0);
      params.append('repairCost', currentSummary.repairCost || 0);
      params.append('otherCost', currentSummary.otherCost || 0);
    }

    // 创建下载链接
    const downloadUrl = `/api/tires/cost-statistics/export?${params}`;
    const fileName = generateExportFileName();

    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 显示成功消息
    showExportSuccessMessage();
  }


  // 生成导出文件名
  function generateExportFileName() {
    const now = new Date();
    const dateStr = now.toISOString().split('T')[0];
    const timeStr = now.toTimeString().split(' ')[0].replace(/:/g, '-');

    const company = document.getElementById('statCompany').value;
    const year = document.getElementById('statYear').value;
    const month = document.getElementById('statMonth').value;
    const statType = document.getElementById('statType').value;

    let fileName = `费用统计报表_${dateStr}_${timeStr}`;

    if (company) fileName += `_${company}`;
    if (year) fileName += `_${year}年`;
    if (month) fileName += `${month}月`;
    if (statType) fileName += `_${getStatTypeText(statType)}`;

    return fileName + '.xlsx';
  }

  // 获取统计类型文本
  function getStatTypeText(statType) {
    const typeMap = {
      'monthly': '月度统计',
      'yearly': '年度统计',
      'vehicle': '单车结算',
      'company': '公司统计'
    };
    return typeMap[statType] || statType;
  }

  // 显示导出成功消息
  function showExportSuccessMessage() {
    // 创建临时提示元素
    const toast = document.createElement('div');
    toast.className = 'position-fixed top-0 start-50 translate-middle-x mt-3 alert alert-success alert-dismissible fade show';
    toast.style.zIndex = '1060';
    toast.innerHTML = `
        <strong>导出成功!</strong> 文件已开始下载。
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(toast);

    // 3秒后自动移除
    setTimeout(() => {
      if (toast.parentNode) {
        toast.remove();
      }
    }, 3000);
  }



  // 打印报表
  function printReport() {
    window.print();
  }
</script>
</body>
</html>